# coding:utf-8

import sys

sys.path.append('/mywork/gitcode-repository/hades/dev-project/adam/src/main/python')

from src.manager.log_manager import LogManager
from src.manager.oracle_manager import OracleManager
from src.config.oracle_config import OracleConfig
import matplotlib.pyplot as plt
from sklearn import preprocessing

Logger = LogManager.get_logger(__name__)


class MdlTopStockDetailHandler:
    """
    股票top100详细信息处理器
    """

    def __init__(self):
        """
        构造函数，初始化oracle_manager和cursor对象
        """
        self.oracle_manager = OracleManager(OracleConfig.Username, OracleConfig.Password, OracleConfig.Url)
        self.oracle_manager.connect()
        self.cursor = self.oracle_manager.get_cursor()

    def paint_mdl_top_stock_by_code(self, code, date_number, period_type):
        """
        根据code，生成这个股票各个周期的涨跌幅度的折线图
        :param code:
        :param date_number:
        :param period_type:
        :return:
        """
        Logger.info('根据code【' + code + '】，生成这个股票周期【' + str(period_type) + '】的涨跌幅度的折线图')

        # 查询日期
        self.cursor.execute(
            "select * from(select t.date_ from mdl_top_stock t order by t.date_ desc) where rownum<=" + str(
                date_number))
        date_list = self.cursor.fetchall()

        # 查询收盘价
        self.cursor.execute(
            "select * from(select t.date_, t.close_price from stock_transaction_data t where t.code_='" + code + "' order by t.date_ desc) where rownum<=" + str(
                date_number))
        date_and_close_price_list = self.cursor.fetchall()

        # 查询period_type为period_type的记录
        # self.cursor.execute(
        #     "select t.date_, t.up_down_percentage from mdl_top_stock_detail t where t.code_='" + code + "' and t.period_type=" + str(
        #         period_type) + " order by t.date_ desc")
        # date_and_up_down_percentage_list = self.cursor.fetchall()
        self.cursor.execute(
            "select t.date_, t.up_down_percentage from mdl_top_stock_detail t where t.code_='" + code + "' and t.period_type=21 order by t.date_ desc")
        date_and_21_up_down_percentage_list = self.cursor.fetchall()
        self.cursor.execute(
            "select t.date_, t.up_down_percentage from mdl_top_stock_detail t where t.code_='" + code + "' and t.period_type=34 order by t.date_ desc")
        date_and_34_up_down_percentage_list = self.cursor.fetchall()
        self.cursor.execute(
            "select t.date_, t.up_down_percentage from mdl_top_stock_detail t where t.code_='" + code + "' and t.period_type=55 order by t.date_ desc")
        date_and_55_up_down_percentage_list = self.cursor.fetchall()

        close_price_list = self.match_by_date(date_list, date_and_close_price_list)
        # up_down_percentage_list = self.match_by_date(date_list, date_and_up_down_percentage_list)
        up_down_percentage_21_list = self.match_by_date(date_list, date_and_21_up_down_percentage_list)
        up_down_percentage_34_list = self.match_by_date(date_list, date_and_34_up_down_percentage_list)
        up_down_percentage_55_list = self.match_by_date(date_list, date_and_55_up_down_percentage_list)

        # plt.plot(date_list, close_price_list)
        # plt.plot(date_list, up_down_percentage_list)
        min_max_scaler = preprocessing.MinMaxScaler()
        up_down_percentage_list = [close_price_list, up_down_percentage_21_list, up_down_percentage_34_list, up_down_percentage_55_list]
        x_minmax_list = min_max_scaler.fit_transform(up_down_percentage_list)
        plt.plot(date_list, close_price_list, color='black')
        plt.plot(date_list, up_down_percentage_21_list)
        plt.plot(date_list, up_down_percentage_34_list)
        plt.plot(date_list, up_down_percentage_55_list)
        plt.title('line chart')
        plt.xlabel('x')
        plt.ylabel('y')
        plt.show()

    def match_by_date(self, date_list, value_list):
        """
        date_list和date_and_up_down_percentage_list的日期如果一致，则将涨跌百分比加入到新数组中，否则加入None。
        最后返回新数组
        :param date_list:
        :param value_list:
        :return:
        """
        if date_list is not None and len(date_list) > 0:
            if value_list is not None and len(value_list) > 0:
                return_list = []
                for date_tuple in date_list:
                    next_date = False
                    temp_value_list = value_list
                    for value_tuple in temp_value_list:
                        date_ = value_tuple[0]
                        value = value_tuple[1]
                        if date_tuple[0] == date_:
                            return_list.append(value)
                            next_date = True
                            break
                    if next_date is True:
                        continue
                    else:
                        return_list.append(None)
                Logger.info(date_list)
                Logger.info(return_list)
                return return_list
            else:
                Logger.warn('参数date_and_up_down_percentage_list为空')
                return None
        else:
            Logger.warn('参数date_list为空')
            return None
